const { app, BrowserWindow, globalShortcut, ipcMain } = require('electron');
const { ICON, closeWhistle, showWin } = require('./util');
const ctx = require('./context');
const { disableProxy, isEnabled, getTitle } = require('./proxy');

let willQuit;
let beforeQuit;

const cleanup = async () => {
  if (isEnabled()) {
    try {
      await disableProxy();
    } catch (err) {}
  }
  closeWhistle();
  app.removeListener('will-quit', handleWillQuit); // eslint-disable-line
};

const handleWillQuit = async (e) => {
  if (willQuit) {
    return app.exit();
  }
  e.preventDefault();
  willQuit = true;
  await cleanup();
  app.exit();
};

const showWindow = () => {
  if (!willQuit) {
    showWin(ctx.getWin());
  }
};

const createWindow = () => {
  const win = new BrowserWindow({
    title: getTitle(),
    fullscreen: false,
    fullscreenable: true,
    icon: ICON,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      spellcheck: false,
      webviewTag: true,
      // 启用开发者工具
      devTools: true,
    },
  });
  
  win.onBeforeFindInPage = function (keyword, opts) {
    const prev = !!opts && !opts.forward;
    keyword = String(keyword).replace(/"/g, '\\"');
    return ctx.execJsSafe(`window.__findWhistleCodeMirrorEditor_("${keyword}", ${prev});`);
  };
  
  // 使用更可靠的按键检测方式
  win.webContents.on('before-input-event', (event, input) => {
    // 检测F12按键（keyCode 123 或 key 'F12'）
    if (input.key === 'F12' || input.keyCode === 123) {
      event.preventDefault();
      event.stopImmediatePropagation();
      console.log('[Whistle] F12按键被检测到并拦截！');
      
      // 切换开发者工具状态
      if (win.webContents.isDevToolsOpened()) {
        win.webContents.closeDevTools();
        console.log('[Whistle] 开发者工具已关闭');
      } else {
        win.webContents.openDevTools();
        console.log('[Whistle] 开发者工具已打开');
      }
      return false;
    }
  });
  
  // 添加额外的按键检测方式
  win.webContents.on('key-down', (event, input) => {
    if (input.key === 'F12' || input.keyCode === 123) {
      event.preventDefault();
      event.stopImmediatePropagation();
      console.log('[Whistle] F12按键按下事件被拦截！');
      
      // 在这里也处理开发者工具切换，确保能捕获到
      if (win.webContents.isDevToolsOpened()) {
        win.webContents.closeDevTools();
        console.log('[Whistle] 通过key-down关闭开发者工具');
      } else {
        win.webContents.openDevTools();
        console.log('[Whistle] 通过key-down打开开发者工具');
      }
      return false;
    }
  });
  
  // 注册右键菜单打开开发者工具
  win.webContents.on('context-menu', (e, params) => {
    if (params.isEditable) {
      return;
    }
    // 添加"检查元素"选项
    const { Menu, MenuItem } = require('electron');
    const menu = new Menu();
    
    // 添加检查元素选项
    menu.append(new MenuItem({
      label: '检查元素',
      click: () => {
        win.webContents.inspectElement(params.x, params.y);
      }
    }));
    
    // 添加分隔线
    menu.append(new MenuItem({ type: 'separator' }));
    
    // 添加开发者工具选项
    menu.append(new MenuItem({
      label: '开发者工具',
      accelerator: 'F12 (主要) 或 Ctrl+F12/Shift+F12',
      click: () => {
        if (win.webContents.isDevToolsOpened()) {
          win.webContents.closeDevTools();
        } else {
          win.webContents.openDevTools();
        }
      }
    }));
    
    menu.popup();
  });
  
  ctx.setWin(win);
  win.setMenu(null);
  win.maximize();
  
  // 添加IPC监听器处理开发者工具切换
  ipcMain.on('toggle-devtools', () => {
    console.log('[Whistle] 收到IPC消息：切换开发者工具');
    if (win && !win.isDestroyed()) {
      if (win.webContents.isDevToolsOpened()) {
        win.webContents.closeDevTools();
        console.log('[Whistle] 通过IPC关闭开发者工具');
      } else {
        win.webContents.openDevTools();
        console.log('[Whistle] 通过IPC打开开发者工具');
      }
    }
  });
  
  // 添加额外的F12检测机制
  win.on('focus', () => {
    console.log('[Whistle] 窗口获得焦点，启用F12检测...');
    
    // 使用setTimeout确保在下一帧执行
    setTimeout(() => {
      // 尝试注册F12快捷键（在窗口级别）
      try {
        const success = globalShortcut.register('F12', () => {
          console.log('[Whistle] 🎉 窗口级F12快捷键被触发！');
          if (win.webContents.isDevToolsOpened()) {
            win.webContents.closeDevTools();
            console.log('[Whistle] 开发者工具已关闭');
          } else {
            win.webContents.openDevTools();
            console.log('[Whistle] 开发者工具已打开');
          }
        });
        
        if (success) {
          console.log('[Whistle] ✅ 窗口级F12快捷键注册成功！');
        } else {
          console.log('[Whistle] ❌ 窗口级F12快捷键注册失败，但键盘事件监听器仍在工作');
        }
      } catch (error) {
        console.log('[Whistle] 窗口级F12快捷键注册出错:', error.message);
      }
    }, 100);
  });
  
  win.on('ready-to-show', () => {
    showWin(win);
    
    // 在窗口显示后再注册F12快捷键，确保窗口已完全准备好
    setTimeout(() => {
      console.log('[Whistle] 窗口级F12快捷键注册开始...');
      
      // 强制注销F12，尝试从系统手中抢回
      try {
        globalShortcut.unregister('F12');
        console.log('[Whistle] 窗口级：已强制注销F12快捷键');
      } catch (error) {
        console.log('[Whistle] 窗口级：注销F12时出错:', error.message);
      }
      
      // 等待一小段时间让系统释放F12
      setTimeout(() => {
        console.log('[Whistle] 窗口级：尝试注册F12快捷键...');
        
        // 专注注册F12
        const successF12 = globalShortcut.register('F12', () => {
          console.log('[Whistle] 🎉 窗口级F12快捷键被触发！');
          if (win && !win.isDestroyed()) {
            if (win.webContents.isDevToolsOpened()) {
              win.webContents.closeDevTools();
              console.log('[Whistle] 开发者工具已关闭');
            } else {
              win.webContents.openDevTools();
              console.log('[Whistle] 开发者工具已打开');
            }
          }
        });
        
        if (successF12) {
          console.log('[Whistle] 🎉 窗口级F12快捷键注册成功！');
          
          // 验证注册状态
          const isRegistered = globalShortcut.isRegistered('F12');
          console.log(`[Whistle] 窗口级F12快捷键状态验证: ${isRegistered ? '已注册' : '未注册'}`);
          
        } else {
          console.log('[Whistle] ❌ 窗口级F12注册失败，但窗口级键盘事件监听器仍在工作');
        }
        
        // 列出所有已注册的快捷键
        try {
          const registeredShortcuts = globalShortcut.getRegisteredShortcuts();
          console.log('[Whistle] 窗口级当前已注册的快捷键:', registeredShortcuts);
        } catch (error) {
          console.log('[Whistle] 获取已注册快捷键时出错:', error.message);
        }
        
      }, 500); // 等待500ms让系统释放F12
      
      console.log('[Whistle] 窗口级F12快捷键注册完成');
    }, 1000); // 延迟1秒确保窗口完全加载
  });
  win.on('close', (e) => {
    if (beforeQuit) {
      return;
    }
    beforeQuit = false;
    e.preventDefault();
    win.hide();
  });
  win.webContents.once('page-title-updated', () => {
    win.setTitle(getTitle());
  });
  
  // 注入JavaScript代码来检测F12按键
  win.webContents.on('did-finish-load', () => {
    console.log('[Whistle] 页面加载完成，注入F12检测代码...');
    
    // 注入F12检测代码
    win.webContents.executeJavaScript(`
      (function() {
        console.log('[Whistle] 注入F12检测代码...');
        
        // 检测F12按键
        document.addEventListener('keydown', function(event) {
          if (event.key === 'F12' || event.keyCode === 123) {
            console.log('[Whistle] JavaScript层检测到F12按键！');
            event.preventDefault();
            event.stopPropagation();
            event.stopImmediatePropagation();
            
            // 发送消息给主进程
            if (window.require) {
              try {
                const { ipcRenderer } = window.require('electron');
                ipcRenderer.send('toggle-devtools');
              } catch (e) {
                console.log('[Whistle] 无法发送IPC消息:', e.message);
              }
            }
            
            return false;
          }
        }, true);
        
        // 阻止默认的F12行为
        document.addEventListener('keyup', function(event) {
          if (event.key === 'F12' || event.keyCode === 123) {
            event.preventDefault();
            event.stopPropagation();
            event.stopImmediatePropagation();
            return false;
          }
        }, true);
        
        console.log('[Whistle] F12检测代码注入完成');
      })();
    `).catch(err => {
      console.log('[Whistle] 注入F12检测代码失败:', err.message);
    });
  });
};

// 应用准备好后注册全局快捷键
app.whenReady().then(() => {
  console.log('[Whistle] 应用已准备就绪，开始注册全局快捷键...');
  
  // 尝试使用更强的F12拦截策略
  console.log('[Whistle] 尝试使用强力F12拦截策略...');
  
  // 方法1：强制注销F12，尝试从系统手中抢回
  try {
    globalShortcut.unregister('F12');
    console.log('[Whistle] 已强制注销F12快捷键');
  } catch (error) {
    console.log('[Whistle] 强制注销F12时出错:', error.message);
  }
  
  // 方法2：尝试注册F12，如果失败则使用备选方案
  setTimeout(() => {
    console.log('[Whistle] 延迟500ms后尝试注册F12...');
    
    const successF12 = globalShortcut.register('F12', () => {
      console.log('[Whistle] 🎉 F12快捷键终于被触发了！');
      const win = ctx.getWin();
      if (win && !win.isDestroyed()) {
        if (win.webContents.isDevToolsOpened()) {
          win.webContents.closeDevTools();
          console.log('[Whistle] 开发者工具已关闭');
        } else {
          win.webContents.openDevTools();
          console.log('[Whistle] 开发者工具已打开');
        }
      }
    });
    
    if (successF12) {
      console.log('[Whistle] 🎉 F12快捷键注册成功！系统终于释放了F12！');
    } else {
      console.log('[Whistle] ❌ F12仍然被系统占用，使用备选方案...');
      
      // 备选方案1：Ctrl+F12
      const successCtrlF12 = globalShortcut.register('Ctrl+F12', () => {
        console.log('[Whistle] Ctrl+F12快捷键被触发！');
        const win = ctx.getWin();
        if (win && !win.isDestroyed()) {
          if (win.webContents.isDevToolsOpened()) {
            win.webContents.closeDevTools();
          } else {
            win.webContents.openDevTools();
          }
        }
      });
      
      if (successCtrlF12) {
        console.log('[Whistle] ✅ Ctrl+F12快捷键注册成功（作为F12的备选）');
      } else {
        console.log('[Whistle] ❌ Ctrl+F12也注册失败');
      }
    }
  }, 500);
  
  // 注册Ctrl+Shift+I快捷键打开开发者工具（作为备选）
  try {
    const successCtrlShiftI = globalShortcut.register('CommandOrControl+Shift+I', () => {
      console.log('[Whistle] Ctrl+Shift+I快捷键被触发！');
      const win = ctx.getWin();
      if (win && !win.isDestroyed()) {
        if (win.webContents.isDevToolsOpened()) {
          win.webContents.closeDevTools();
        } else {
          win.webContents.openDevTools();
        }
      }
    });
    
    if (successCtrlShiftI) {
      console.log('[Whistle] ✅ Ctrl+Shift+I快捷键注册成功');
    } else {
      console.log('[Whistle] ❌ Ctrl+Shift+I快捷键注册失败');
    }
  } catch (error) {
    console.log('[Whistle] Ctrl+Shift+I快捷键注册出错:', error.message);
  }
  
  // 列出所有已注册的快捷键
  try {
    const registeredShortcuts = globalShortcut.getRegisteredShortcuts();
    console.log('[Whistle] 当前已注册的全局快捷键:', registeredShortcuts);
  } catch (error) {
    console.log('[Whistle] 获取已注册快捷键时出错:', error.message);
  }
  
  console.log('[Whistle] 全局快捷键注册完成');
});

app.on('before-quit', () => {
  beforeQuit = true;
});
app.on('activate', showWindow);
app.on('will-quit', handleWillQuit);

exports.willQuit = () => willQuit;

exports.showWindow = showWindow;

exports.createWindow = createWindow;

exports.restart = async () => {
  willQuit = true;
  await cleanup();
  app.relaunch({ args: process.argv.slice(1).concat(['--relaunch']) });
  app.exit();
};
